﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using ZFY.Blog.Api.Model;
using ZFY.Blog.Api.Model.Model;
using Autofac;
using Hangfire;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using StackExchange.Redis;
using ZFY.AspNetCore;

namespace ZFY.Blog.Api
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers(x =>
            {
                // 全局异常过滤
                x.Filters.Add(typeof(UOWActionFilter));
                x.Filters.Add(typeof(ZFYResultFilter));
            })
              .AddNewtonsoftJson(options =>
            {
                //忽略循环引用
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                //设置时间格式
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
            });
            services.AddHangfire(x => x.UseRedisStorage(ConnectionMultiplexer.Connect("localhost,password=root")));
            services.AddDbContext<BlogApiDbContext>(x =>
            {
                ILoggerFactory MyLoggerFactory = LoggerFactory.Create(builder =>
                {
                    builder
                        .AddFilter((category, level) =>
                            category == DbLoggerCategory.Database.Command.Name
                            && level == LogLevel.Information)
                        .AddConsole();
                });
                x.UseSqlite(Configuration.GetConnectionString("SqlLite")).UseLoggerFactory(MyLoggerFactory);
            });
            services.AddSwaggerGen(x => x.SwaggerDoc("v1", new (){ Title = "ZFY.Blog.Api", Version = "v1" }));
            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
            //services.AddAssembly("ZFY.Blog.Api.Repository");
            //services.AddAssembly("ZFY.Blog.Api.Services");
            var cors = Configuration["Cors"].Split(",");
            services.AddCors(x => x.AddPolicy("cors", policy => policy.AllowCredentials().AllowAnyMethod().AllowAnyHeader().WithOrigins(cors)));
            //services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            //.AddJwtBearer(options =>
            //{
            //    // base-address of your identityserver
            //    options.Authority = "http://localhost:6001";
            //    options.RequireHttpsMetadata = false;
            //    // name of the API resource
            //    options.Audience = "BlogZFY.Blog.Api";
            //});
            services.AddHostedService<CustomerService>();
            services.AddHttpContextAccessor();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseHangfireServer();
            app.UseHangfireDashboard();
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "ZFY.Blog.Api");
                // 将swagger首页，设置成我们自定义的页面，记得这个字符串的写法：解决方案名.index.html
                c.RoutePrefix = "swagger"; //路径配置，设置为空，表示直接在根域名（localhost:8001）访问该文件,注意localhost:8001/swagger是访问不到的，去launchSettings.json把launchUrl去掉，如果你想换一个路径，直接写名字即可，比如直接写c.RoutePrefix = "doc";
                c.InjectJavascript("/SwaggerChinese.js");
            });
            StaticInfo.ContentRootPath = env.ContentRootPath;
            StaticInfo.WebRootPath = env.WebRootPath;
            InitializeDatabase(app);
            app.UseCors("cors");
            app.UseStaticFiles();
            // 返回错误码
            app.UseStatusCodePages();//把错误码返回前台，比如是404
            app.UseRouting();
            //app.UseAuthentication();
            //app.UseAuthorization();
            app.UseZFY();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                   name: "default",
                   pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
        private void InitializeDatabase(IApplicationBuilder app)
        {
            using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
            {


                var context = serviceScope.ServiceProvider.GetRequiredService<BlogApiDbContext>();
                context.Database.Migrate();
                if (!context.Article.Any())
                {
                    var body = "# 非淡泊无以明志，非宁静无以致远  \n" +
                        "不看清世俗的名利就不能明确自己的志向，身心不宁静就无法实现远大的理想。";
                    File.WriteAllText(StaticInfo.WebRootPath + "/Article/first.md", body);
                    var article = new Article
                    {
                        Id = 1,
                        Digest = "非淡泊无以明志，非宁静无以致远",
                        Support = 999,
                        Visited = 999,
                        Comment = 999,
                        Title = "淡泊明志，宁静致远",
                        Url = "/Article/first.md",
                        CreationTime = DateTime.Now,
                        ArticleType = new ArticleType
                        {
                            Id = 1,
                            Name = "修身养性",
                            Meun = Model.Enum.MeunEnum.资源分享,
                            Image = "/ArticleTypeImage/1783d300-5cad-4050-8ecd-d59c37c5351b.jpg",
                            CreationTime = DateTime.Now
                        },
                        TagArticles = new List<TagArticle>
                        {
                            new TagArticle
                            {
                                Tag = new Tag
                                {
                                    Name="处世",
                                    CreationTime = DateTime.Now
                                }
                            }
                        }
                    };
                    context.Article.Add(article);
                    context.SaveChanges();
                }
            }
        }
        public void ConfigureContainer(ContainerBuilder containerBuilder)
        {
            containerBuilder.RegisterModule<ZFYAutofacModule>();
        }
    }
}
